import sys
import os
import argparse
from loguru import logger
from root_agent.rootAgent import RootAgent
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
import json

def load_settings():
    settings = {}
    try:
        with open('settings.txt', 'r', encoding='utf-8') as f:
            settings = json.load(f)
    except FileNotFoundError:
        logger.error("settings.txt not found. Please create one.")
    except json.JSONDecodeError:
        logger.error("Error decoding JSON from settings.txt. Please check the file format.")
    return settings

settings = load_settings()
default_userid = settings.get("userid", "test111")
default_openid = settings.get("openid", "zyinfoai")
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import uvicorn

from context_manager import ContextManager
from output_generator import OutputGenerator
from input_processor import InputProcessor

# Configure logger
logger.remove()
import os
from loguru import logger

# Remove existing handlers to prevent file locking issues
logger.remove()

if os.path.exists("saia_log.log"):
    try:
        os.remove("saia_log.log")
        logger.info("Successfully removed saia_log.log")
    except OSError as e:
        logger.error(f"Error removing saia_log.log: {e}")

logger.add("saia_log.log", rotation="200 KB", level="INFO", filter=lambda record: record["name"] != "tools.tool_manager")


root_agent = RootAgent(userid=default_userid, openid=default_openid)
context_manager = ContextManager()
output_generator = OutputGenerator()

def create_web_app():
    app = FastAPI()

    @app.get("/chat", response_class=HTMLResponse)
    @app.get("/chat/", response_class=HTMLResponse, include_in_schema=False) # 同时处理带斜杠和不带斜杠
    async def get_chat_page():
        """
        为 /chat 路径显式提供 index.html 文件。
        这是比 app.mount(..., html=True) 更清晰、更直接的方式。
        """
        chat_html_path = os.path.join("static", "index.html")
        if not os.path.exists(chat_html_path):
            return HTMLResponse(content="<h1>Error: chat/index.html not found</h1>", status_code=404)
        with open(chat_html_path, "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
        

    # 1. 挂载主UI (npx构建的应用)
    #    - URL路径 `/` 会服务 `web_ui/index.html`
    #    - URL路径 `/static/...` 会服务 `web_ui/static/...` 目录下的文件
    
    app.mount("/static", StaticFiles(directory="web_ui/static"), name="ui_static")
    
    # 2. 挂载第二个聊天界面
    #    - 为了避免与主UI的 `/static` 冲突，我们将第二个界面的静态资源目录挂载到 `/chat_static`
    #    - 这样，`static/index.html` 中引用的 `style.css` 应该使用路径 `/chat_static/style.css`
    #app.mount("/chat", StaticFiles(directory="static"), name="chat_static")

    # @app.get("/chat", response_class=HTMLResponse)
    # async def read_root():
    #     with open(os.path.join(os.getcwd(), "static", "index.html"), "r") as f:
    #         return HTMLResponse(content=f.read())

    @app.post("/api/prompt")
    async def handle_prompt(request: Request):
        data = await request.json()
        processed_input = InputProcessor.process_input("web", data)
        user_input = processed_input["user_input"]
        file_context = processed_input["file_context"] # Currently empty for web, but for future compatibility

        if not user_input:
            return JSONResponse(content={"response": "No prompt provided."}, status_code=400)

        logger.info(f"Web UI input: {user_input}")
        context_manager.update_history("user", user_input)
        
        # Pass the full context to the root agent, including file_context from processed_input
        current_context = context_manager.get_context()
        current_context["file_context"] = file_context # Add file_context to the current_context
        response_data = root_agent.process_command(user_input, current_context)
        final_result_content = response_data.get("final_result", "No final result.")
        llm_metrics = response_data.get("llm_usage_metrics", {})

        context_manager.update_history("assistant", final_result_content)
        logger.info(f"SAIA response: {final_result_content}")
        
        # Generate natural language response for the web UI
        return JSONResponse(content={
            "response": output_generator.generate_nlp_output(final_result_content),
            "llm_metrics": llm_metrics,
            "total_task_duration": response_data.get("total_task_duration", 0.0)
        })

    @app.get("/api/evolution_status")
    async def get_evolution_status():
        status = root_agent.self_evolution_agent.get_status()
        return JSONResponse(content=status)

    @app.post("/api/tasks/{task_id}/pause")
    async def pause_task(task_id: str):
        root_agent.pause_task(task_id)
        return JSONResponse(content={"message": f"Task {task_id} paused."})

    @app.post("/api/tasks/{task_id}/resume")
    async def resume_task(task_id: str):
        root_agent.resume_task(task_id)
        return JSONResponse(content={"message": f"Task {task_id} resumed."})

    @app.post("/api/tasks/{task_id}/cancel")
    async def cancel_task(task_id: str):
        root_agent.cancel_task(task_id)
        return JSONResponse(content={"message": f"Task {task_id} cancelled."})

    @app.get("/api/tasks/{task_id}/status")
    async def get_task_status(task_id: str):
        status = root_agent.get_task_status(task_id)
        return JSONResponse(content=status)

    @app.get("/api/tasks")
    async def get_all_tasks_status():
        all_tasks_status = {}
        for task_id, state in root_agent.task_states.items():
            all_tasks_status[task_id] = state
        return JSONResponse(content=all_tasks_status)

    @app.get("/api/metrics")
    async def get_metrics():
        metrics = root_agent.get_llm_metrics()
        return JSONResponse(content=metrics)

    @app.get("/api/memory_status")
    async def get_memory_status():
        status = root_agent.get_memory_status()
        return JSONResponse(content=status)
    
    app.mount("/", StaticFiles(directory="web_ui", html=True), name="ui")
    return app

def main():
    app = create_web_app()
    uvicorn.run(app, host="0.0.0.0", port=8003)


if __name__ == "__main__":
    main()

